package com.hmdp.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.Session;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author dlc
 * @Date 2023/11/9
 * @Description TODO
 * @Version 0.0.1
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 只需要判断是否存在用户就行了
        if(UserHolder.getUser() == null) {
            response.setStatus(401);
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求之后删掉这个用户
        UserHolder.removeUser();
    }

    // Session实现的版本
/*
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取session
        HttpSession session = request.getSession();
        // 获取用户
        Object user = session.getAttribute("user");
        // 判断用户
        if(user == null) {
            response.setStatus(401);
            // 拦截
            return false;
        }
        // 存在，保存用户到LocalThread
        UserHolder.saveUser((UserDTO) user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求之后删掉这个用户
        UserHolder.removeUser();
    }
*/
}
